/*
 * EZCP_Sim_Receive.c
 *
 *  Created on: Apr 18, 2011
 *      Author: Group 8
 */

#include "EZCP_Sim_Common.h"

name_attach_t *pst_nameattach_attach=NULL;
//Size in bytes of each Message ID
extern unsigned int MSG_DATA_LENGTHS [EZCP_NUM_OF_MSGS];
void MsgGUIDisplay (u8 ui_msgid, u32 ui_data_len, msg_data_buf_t buf_data);

void *pf_Receiver()
{
	//Create channel to receive from App
	EZCP_Simu_CreateChannel();

	//Start receive and processing of messages
	EZCP_Simu_RecvOutgoingMsg();

	return NULL;
}


//Interface with the Application to receive messages
void EZCP_Simu_CreateChannel()
{
	print ("%s: Attach Channel with Application\n",__func__);

	if (NULL == (pst_nameattach_attach = name_attach(NULL, EZCP_ATTACH_APP2SIMU, 0)))
	{
		err (-1,"%s: name_attach error", __func__);
	}

}

//Receive messages from Application
void EZCP_Simu_RecvOutgoingMsg()
{
	s32 si_RcvId,si_Ret;

	msg_header_t st_my_hdr;
	msg_data_buf_t buf_data;
	MsgBuffer MsgReceived;

	if (NULL == pst_nameattach_attach)
	{
		err (-1,"EZCP service: channel not available for receiving simulation...");
	}

	while (1)
	{
		print ("%s: Waiting to receive Application data ...\n",__func__);
		si_RcvId = MsgReceive(pst_nameattach_attach->chid, &st_my_hdr, EZCP_HDR_LEN, NULL);
		if (-1 == si_RcvId )
		{/* Error condition, exit */
			err (-1,"%s: MsgReceive error",__func__);
		}

		if (0 == si_RcvId)
		{// pulse received
			if (_PULSE_CODE_DISCONNECT == st_my_hdr.code)
				break;
			continue;
		}

		/* name_open() from Application sends a connect message, must EOK this */
		if (_IO_CONNECT  == st_my_hdr.type)
		{
			//Acknowledge receipt of message
			MsgReply( si_RcvId, EOK, NULL, 0 );
			continue;
		}

		/* Some other QNX IO message was received; reject it */
		if (st_my_hdr.type > _IO_BASE && st_my_hdr.type <= _IO_MAX )
		{
			MsgError( si_RcvId, ENOSYS );
			continue;
		}

		/* A message (presumably ours) received, handle */
		print ("%s: Message Received from Application\n",__func__);
		si_Ret = MsgRead(si_RcvId, buf_data, st_my_hdr.subtype, sizeof(st_my_hdr));
		if (-1 == si_Ret)
		{/* Error condition, exit */
			err (-1,"%s: MsgRead error",__func__);
		}

		MsgReceived.MsgID = st_my_hdr.type ;
		MsgReceived.Length = st_my_hdr.subtype ;
		memcpy (MsgReceived.Data,buf_data,sizeof(msg_data_buf_t));

		//print ("%s: Message ID Receieved = %d\n",__func__,MsgReceived.MsgID);

	    //Display sent msg on GUI
	    MsgGUIDisplay (MsgReceived.MsgID, MsgReceived.Length, MsgReceived.Data);

		MsgReply(si_RcvId, EOK, 0, 0);
	}//end of while(1)

	/* Remove the name from the space */
	name_detach(pst_nameattach_attach, 0);
}
